package com.neusoft.neuiotms.dcom.service.impl;

import java.util.List;

import javax.persistence.EntityNotFoundException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.neusoft.bizcore.web.constant.ExceptionConstants;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.converter.ClassesConverter;
import com.neusoft.neuiotms.dcom.dto.ClassesDTO;
import com.neusoft.neuiotms.dcom.model.Classes;
import com.neusoft.neuiotms.dcom.repository.ClassesRepository;
import com.neusoft.neuiotms.dcom.service.ClassesService;

@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassesRepository classesRepository;
    @Autowired
    private ClassesConverter classesConverter;

    @Override
    public List<ClassesDTO> index(final Searchable searchable) {
        final List<Classes> models = this.classesRepository.index(searchable);
        return this.classesConverter.toListDTO(models);
    }

    @Override
    public Page<ClassesDTO> search(final Pageable pageable, final Searchable searchable) {
        final Page<Classes> result = this.classesRepository.search(pageable, searchable);
        return this.classesConverter.toPageDTO(result);
    }

    @Override
    public ClassesDTO create(final ClassesDTO dto) {

        final Classes model = this.classesConverter.toModel(dto);
        this.classesRepository.save(model);

        return this.classesConverter.toDTO(model);
    }

    @Override
    public ClassesDTO update(final Long id, final ClassesDTO dto) {

        Classes model;

        try {
            model = this.classesRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        dto.setId(model.getId());
        model = this.classesConverter.toModel(dto);
        this.classesRepository.save(model);

        return this.classesConverter.toDTO(model);
    }

    @Override
    public ClassesDTO details(final Long id) {

        Classes model;

        try {
            model = this.classesRepository.getOne(id);
        } catch (final EntityNotFoundException e) {
            throw new UnitedException(ExceptionConstants.ENTITY_NOT_FOUND, new Object[] {id });
        }

        return this.classesConverter.toDTO(model);
    }

    @Override
    public void delete(final Long id) {

        try {

            this.classesRepository.deleteById(id);

        } catch (final Exception e) {

            throw new UnitedException("此班次制度已经安排值班，不能删除");
        }

    }

}
